package router

import (
	"github.com/gin-gonic/gin"
	"github.com/lexkong/log"
	"html/template"
	"net/http"
	"time"
	"webProject/handler"
	"webProject/handler/sd"
	"webProject/handler/stream"
	"webProject/handler/user"
	"webProject/model"
	"webProject/pkg/constvar"
	"webProject/router/middleware"
)

func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine {
	//在处理某些请求时可能因为程序 bug 或者其他异常情况导致程序 panic，
	// 这时候为了不影响下一次请求的调用，需要通过 gin.Recovery()来恢复 API 服务器
	g.Use(gin.Recovery())
	//强制浏览器不使用缓存
	g.Use(middleware.NoCache)
	//浏览器跨域 OPTIONS 请求设置
	g.Use(middleware.Options)
	//一些安全设置
	g.Use(middleware.Secure)
	//关于RequestID的设置
	g.Use(middleware.RequestId())
	g.Use(mw...)
	//加载HTML模板文件
	g.LoadHTMLGlob("templates/**/*")
	g.LoadHTMLFiles("templates/index.tmpl")
	//加载静态文件
	g.Static("/static", "./static")
	//设置模板函数
	g.SetFuncMap(template.FuncMap{
		"safe": func(str string) template.HTML {
			return template.HTML(str)
		},
	})
	//设置文件上传的最大大小
	g.MaxMultipartMemory = constvar.MaxUploadSize
	//404
	g.NoRoute(func(g *gin.Context) {
		g.String(http.StatusNotFound, "The incorrect API route.")
	})

	g.POST("/login", user.Login)

	u := g.Group("/v1/user")
	u.Use(middleware.AuthMiddleware())
	{
		u.POST("", user.Create)
		u.DELETE("/:id", user.Delete)
		u.PUT("/:id", user.Update)
		u.GET("", user.List)
		u.GET("/:username", user.Get)
	}
	svcd := g.Group("/sd")
	{
		svcd.GET("/health", sd.HealthCheck)
		svcd.GET("/disk", sd.DiskCheck)
		svcd.GET("/cpu", sd.CPUCheck)
		svcd.GET("/ram", sd.RAMCheck)
	}
	g.GET("/post/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "post/index.html", gin.H{
			"tittle": "post/index",
		})
	})
	g.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", "<a href='https://liwenzhou.com'>李文周的博客</a>")
	})
	g.POST("/file/upload",stream.UploadHandler)
	g.GET("/file/download",stream.DownLoadHandler)
	vueGroup := g.Group("/vue")
	{
		vueGroup.GET("/getprodlist", func(g *gin.Context) {
			 proList,err := model.GetProductList()
			 if err !=nil{
				 handler.SendResponse(g,err,nil)
			 }
				handler.SendResponse(g,nil,proList)
		})
		vueGroup.POST("/product", func(g *gin.Context) {
			name := g.Query("name")
			log.Infof("name:%s \n",name)
			product := model.Product{
				Name:       name,
				CreateTime: time.Now(),
			}
			err := product.CreateProduct()
			if err !=nil{
				handler.SendResponse(g,err,nil)
				return
			}
			handler.SendResponse(g,nil,product)
		})
	}

	return g
}
